package com.example.gallery;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class Common extends Activity{
	private String TAG = "COMMON";
	ArrayList<AlbumDTO> list = null;
	static final File album_root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);	//storage/emulated/0
	ArrayList<ImageDTO> image_list;
	
	
	
	public void go(Context ctx, Class c){
		Intent intent = new Intent(ctx, c);
		startActivity(intent);
		Log.i(TAG, "go "+c);
		finish();
	}
	
//	갤러리 폴더 이름
	public ArrayList<AlbumDTO> getAlbumList(){
		Log.i(TAG, "album_root : "+album_root);
		int n = 0;
		list = new ArrayList<AlbumDTO>();
		String[] path_list = album_root.list();	//storage/emulated/0/  하위 리스트 목록 가져옴
		Log.i(TAG, "폴더 수 : "+ path_list.length);
		
		for(int i=0; i<path_list.length; i++){
			AlbumDTO dto = new AlbumDTO();
			n = countImageFile(path_list[i]);
			Log.i(TAG, "path_list["+i+"] : "+path_list[i]+"\n사진갯수: "+n);
			
			dto.setA_name(path_list[i]);
			dto.setA_count(n);
			getImageFile(path_list[i]);
			list.add(dto);
			}
		return list;
	}

	//	폴더 별 사진 개수 
	public int countImageFile(String file_path){
		int num = 0;
		File path = new File(album_root+"/"+file_path);
		Log.i(TAG, "path : "+path);
		if(path.isDirectory()){
			File[] image_file = path.listFiles();
			Log.i(TAG, "# of image_file : "+image_file.length);
			num = image_file.length;
		}
		return num;
	}
	
//	각 앨범별 이미지 가져오기
	public ArrayList<AlbumDTO> getImageFile(String file_path){
		HashMap<String, Object> map = null;
		AlbumDTO dto;
		ArrayList list = new ArrayList<AlbumDTO>();
		File path = new File(album_root+"/"+file_path);
		Log.i(TAG, "path : "+path);
		
		if(path.isDirectory()){
			File[] image_file = path.listFiles();
			Log.i(TAG, "# of image_file : "+image_file.length);
			map = new HashMap<String, Object>();
			
			for(int i=0; i<image_file.length; i++){
				dto = new AlbumDTO();
//				Log.i(TAG, "file_name[ "+i+"] : "+ image_file[i]);
				dto.setA_image(image_file[i]+"");
				list.add(dto);
			}
//			map.put("image_file", list);
		
		/*	
		  	File[] files = path.listFiles(new FilenameFilter() {
				if(files.length != 0){
					for(int i=0; i>files.length; i++){
						Log.i(TAG,"file_path : "+file_path +"file_name : "+files[i]);
					}
				}
				@Override
				public boolean accept(File dir, String filename) {
					File file = new File(dir, filename);
					if(file.isFile() && !file.isHidden() && filename.matches("^.*\\.(?i)(jpg|png|bmp|gif)$")){
						return true;
					}
					return false;
				}
			});
		*/
			
		}
		return list;
	}
	
	
	
	public File getDir(){
		String storagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/GalleryBoard";		//storage/emulated/0/Pictures/Board
//		File pic_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);						//storage/emulated/0/Pictures
//		String pic_parent_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getParent();	//storage/emulated/0
		

		
	/*	Log.i(TAG, "getDir() : "+storagePath);
		Log.i(TAG, "pic_path : "+pic_path);
		Log.i(TAG, "pic_parent_path : "+pic_parent_path);
	*/
	
		File storageDir = new File(storagePath);
			if(!storageDir.exists()){
				storageDir.mkdirs();
			}
//			Log.i(TAG, "storageDir : "+storageDir+"");
//			Log.i(TAG, "storagePath : "+storagePath+"");
		return storageDir;
	}
	
//	real image file path pick from album Uri to File PATH
	public String getRealImagePath (Context mcontext, Uri uriPath)
	{
		String []proj = {MediaStore.Images.Media.DATA};
//		Cursor cursor =  managedQuery(uriPath, proj, null, null, null);
		Cursor image_cursor = null;
		image_cursor = mcontext.getContentResolver().query(uriPath, proj, null, null, null);
		int index = image_cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		image_cursor.moveToFirst();
		String path = image_cursor.getString(index);
		Log.i(TAG, path);
		return path;
	}
	
	public ArrayList<ImageDTO> getLastImage(Context context){
		long returnValue = 0;
		Uri uri = null;
		image_list = new ArrayList<ImageDTO>();
		int data_column ; 
		int imageDataCol;
		String [] IMAGE_PROJECTION = {	   MediaStore.Images.ImageColumns._ID
										  ,MediaStore.Images.ImageColumns.DATA					// image path 
									/*	
									 * 
										, MediaStore.Images.ImageColumns.DATE_TAKEN			// captured time
										, MediaStore.Images.ImageColumns._COUNT				// # of images 
										, MediaStore.Images.Media.BUCKET_ID
									*/
									};
		int id = 0;
		try{
			Uri content_uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
			Log.i(TAG, "content_uri : "+content_uri);
			Cursor image_cursor = null;
			String order = MediaStore.Images.Media.DATE_ADDED + " DESC";
//			Cursor cursor = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, null, null, null);
			
			
			/*
			 * Error : make sure the cursor is initialized correctly before accessing data from it
				CursorWindow 1MB의 용량제한.. ICS 부터 2MB(제조사별로 다름)
			*/
			
			image_cursor = context.getContentResolver().query(
												content_uri												
												, IMAGE_PROJECTION 			//which columns to return
												, null						// WHERE clause; which rows to return(all rows); selection
												, null 						// WHERE clause selection arguments(none); selectionArgs
												, order						//order by clause
												);
			
		/*	int image_coulmn_index = image_cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);*/
//			int image_count = image_cursor.getCount();
			
			if(image_cursor != null && image_cursor.getCount() > 0 ){
				data_column = image_cursor.getColumnIndex(MediaStore.Images.Media._ID);
				imageDataCol = image_cursor.getColumnIndex(MediaStore.Images.Media.DATA);
				
//				String image_name = "";	//이미지 파일명
				if(image_cursor.moveToNext()){
					ImageDTO dto = new ImageDTO();
					dto.setNAME(image_cursor.getString(imageDataCol));
//					dto.setChecked(false);
					Log.i(TAG, dto.getNAME());
					
					image_list.add(dto);
//					uri = Uri.parse(image_cursor.getString(0));	//
//					id = image_cursor.getInt(1);
//					Log.i(TAG, "DATE_TAKEN : "+getString(2));
//					Log.i(TAG, "COUNT : "+getString(3));
				};
			}
			image_cursor.close();
		}
		catch(Exception e){
			e.printStackTrace();
			Log.i(TAG, "getLastImage Exception : "+e.toString());
		}
		return image_list;
		
	}

/*	
	public String[] makeThumbnail(String des_path, String[] orig_file){
		Builder builder;
		String[] files = null;
		
		for(int i=0; i<orig_file.length; i++){
			files[i] = "Thumbnail_"+orig_file[i];
			
			try {
				net.coobird.thumbnailator.Thumbnails.of(orig_file[i]).size(60, 40).toFile(new File(des_path+"/"+files[i]));
				Log.i(TAG,"Thumbnail : "+ des_path+"/"+files[i]);
			} catch (IOException e) {
				e.printStackTrace();
			};

		}
		return files;
	}
*/
	
//	public void getThumbList
	
	
	
}
